<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <link rel="stylesheet" href="css/shoppingcart.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<header>
    <div class="logo">
        <img src="img/logo.png" alt="购物网站标志">
    </div>
    <div class="user-info">
    </div>
</header>

<nav>
    <ul>
        <li><a href="home.html">首页</a></li>
        <li><a href="shoppingcart.html">购物车</a></li>
        <li>
            <a >我的订单</a>
            <ul class="dropdown">
                <li><a href="order.html#all">历史订单</a></li>
                <li><a href="order.html#unpaid">待支付</a></li>
                <li><a href="order.html#paid">已支付</a></li>
                <li><a href="order.html#uncommented">待评价</a></li>
                <li><a href="order.html#commented">已评价</a></li>
            </ul>
        </li>
        <li>
            <a >设置</a>
            <ul class="dropdown">
                <li><a href="setting.html#profile">个人信息</a></li>
                <li><a href="setting.html#change-password">修改密码</a></li>
            </ul>
        </li>
    </ul>
</nav>

<main>
    <div class="select-all">
        <input type="checkbox" id="select-all"> 全选
    </div>
    <div class="footer-summary">
        <span id="total-count">已选择 0 件商品</span>
        <span id="total-price">总价：¥0.00</span>
    </div>
    <table class="product-list">
        <thead>
        <tr>
            <th>选择</th>
            <th>商品图片</th>
            <th>商品名称</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
    <button class="delete-selected-button">删除已选择的商品</button>
    <button class="checkout-button">去结算</button>
</main>

<footer>
    <p>&copy; 购物网站。</p>
</footer>
<script>
    $(document).ready(function() {
        getMyCart(); // 获取购物车商品
        function getMyCart() {
            $.ajax({
                url: "/product/get-cart",
                type: "post",
                success:function(products) {
                    updateProductList(products); // 更新商品列表
                },
                error: function () {
                    alert("登陆已失效，请重新登陆");
                    location.href="login.html"; // 跳转到登录页面
                }
            });
        }

        function updateProductList(products) {
            const productListElement = $('.product-list tbody');
            productListElement.empty();

            if (!products.data || products.data.length === 0) {
                productListElement.append('<tr><td colspan="6">购物车为空</td></tr>');
                updateSummary(0, 0); // 更新汇总信息为零
                return;
            }
            products.data.forEach(product => {
                const productElement = $(`
    <tr data-price="${product.price}" data-id="${product.id}">
        <td><input type="checkbox" class="select-product" value="${product.id}"></td>
        <td><img src="${product.img}" alt="${product.name}" style="width: 80px; height: 80px;"></td>
        <td>${product.name}</td>
        <td>￥${product.price}</td>
        <td class="quantity-control">
            <button class="decrease">-</button>
            <input type="number" class="quantity-input" value="${product.quantity}" min="1" readonly>
            <button class="increase">+</button>
        </td>
        <td><button class="delete-button" data-id="${product.id}">删除商品</button></td>
    </tr>`);
                productListElement.append(productElement);
            });

            attachQuantityHandlers(); // 绑定数量控制事件
            updateSummary(0, 0); // 初始化汇总信息
        }

        function updateSummary(count, price) {
            $('#total-count').text(`已选择 ${count} 件商品`);
            $('#total-price').text(`总价：¥${price.toFixed(2)}`);

        }

        function attachQuantityHandlers() {
            $('.product-list').on('click', '.decrease', function () {
                const quantityInput = $(this).siblings('.quantity-input');
                let quantity = parseInt(quantityInput.val(), 10);
                if (quantity > 1) {
                    quantityInput.val(quantity - 1);
                    updateProductQuantity($(this).closest('tr').data('id'), quantity - 1);
                }
                updateTotals(); // 更新总计
            });

            $('.product-list').on('click', '.increase', function () {
                const quantityInput = $(this).siblings('.quantity-input');
                const newQuantity = parseInt(quantityInput.val(), 10) + 1;
                quantityInput.val(newQuantity);
                updateProductQuantity($(this).closest('tr').data('id'), newQuantity);
                updateTotals(); // 更新总计
            });

            $('.product-list').on('click', '.select-product', updateTotals); // 选中商品更新总计

            $('#select-all').on('change', function () {
                const isChecked = $(this).is(':checked');
                $('.select-product').prop('checked', isChecked);
                updateTotals(); // 更新总计
            });

            $('.product-list').on('click', '.delete-button', function () {
                if (confirm("确认要移除该商品？")) {
                    delMyCart($(this).data('id')); // 删除商品
                }
            });

            $('.delete-selected-button').on('click', function () {
                const selectedProducts = $('.select-product:checked');
                if (selectedProducts.length === 0) {
                    return alert("请先选择要删除的商品");
                }

                if (confirm("确认要删除所选商品吗？")) {
                    const idsToDelete = selectedProducts.map(function () {
                        return $(this).val();
                    }).get();

                    idsToDelete.forEach(delMyCart); // 批量删除商品
                    const alertBox = document.createElement('div');
                    alertBox.className = 'alert-box'; // 添加样式类
                    alertBox.textContent = "移除成功";
                    document.body.appendChild(alertBox);
                    // 设置定时器，在1秒后自动关闭弹窗
                    setTimeout(() => {
                        alertBox.classList.add('fade-out'); // 加入渐变消失效果
                        setTimeout(() => {
                            alertBox.remove(); // 从DOM中移除
                        }, 500); // 等待渐变效果完成后再移除
                    }, 1000);
                }
            });

            $('.checkout-button').on('click', function() {
                const selectedProducts = $('.select-product:checked');
                if (selectedProducts.length === 0) {
                    return alert("请先选择要结算的商品");
                }
                const totalPrice = updateTotals(); // 更新总计
                function generateRandomTraceNo() {
                    var randomPart = Math.floor(Math.random() * 900000 + 100000).toString(); // 生成6位随机数字
                    return "P" + randomPart;
                }

                var traceNo = generateRandomTraceNo();


                const orderData = selectedProducts.map(function() {
                    const $row = $(this).closest('tr');
                    return {
                        id: $(this).val(),
                        quantity: parseInt($row.find('.quantity-input').val(), 10),
                        unitPrice: parseFloat($row.data('price'))
                    };
                }).get();

                for(let i = 0; i < orderData.length; i++)
                {
                    $.ajax({
                        url: "/order/create",
                        type: "post",
                        data: {
                            pid: orderData[i].id,
                            quantity: orderData[i].quantity,
                            unitPrice: orderData[i].unitPrice,
                            traceNo: traceNo
                        },
                        success: function (response) {
                            if (response.state === 200) {
                                var phone = "购买商品";
                                window.open(`http://localhost:9000/alipay/pay?traceNo=${traceNo}&totalAmount=${totalPrice}&subject=${phone}`, '_blank');
                            } else {
                                console.log(orderData);
                                alert("订单生成失败，请重试");
                            }
                        },
                        error: function () {
                            console.log(orderData);
                            alert("遇到错误，请检查连接");
                        }
                    });
                }
            });

        }

        function updateTotals() {
            let totalPrice = 0;
            let totalCount = 0;

            $('.product-list tbody tr').each(function() {
                const quantity = parseInt($(this).find('.quantity-input').val(), 10);
                const price = parseFloat($(this).data('price'));
                const isChecked = $(this).find('.select-product').is(':checked');

                if (isChecked) {
                    totalPrice += price * quantity;
                    totalCount += quantity;
                }
            });
            updateSummary(totalCount, totalPrice); // 更新汇总信息
            return totalPrice;
        }

        function delMyCart(pid) {
            $.ajax({
                url: "/product/del-cart",
                type: "post",
                dataType: "json",
                data: { pid: pid },
                success:function() {
                    getMyCart() // 重新获取购物车
                    const alertBox = document.createElement('div');
                    alertBox.className = 'alert-box'; // 添加样式类
                    alertBox.textContent = "移除成功";
                    document.body.appendChild(alertBox);
                    // 设置定时器，在1秒后自动关闭弹窗
                    setTimeout(() => {
                        alertBox.classList.add('fade-out'); // 加入渐变消失效果
                        setTimeout(() => {
                            alertBox.remove(); // 从DOM中移除
                        }, 500); // 等待渐变效果完成后再移除
                    }, 1000);
                },
                error: function () {
                    alert("移除失败，请重试");
                }
            });
        }

        function updateProductQuantity(pid, quantity) {
            $.ajax({
                url: "/product/up-cart",
                type: "post",
                dataType: "json",
                data: { pid: pid, quantity: quantity },
                success: function (response) {
                    if (response.state === 200) {
                        console.log("数量更新成功");
                    } else {
                        alert("数量更新失败，请重试");
                    }
                },
                error: function () {
                    alert("遇到错误，请检查连接");
                }
            });
        }

        function checkOut() {
            $('.checkout-button').on('click', function() {
                const selectedProducts = $('.select-product:checked');
                if (selectedProducts.length === 0) {
                    return alert("请先选择要结算的商品");
                }

                const orderData = selectedProducts.map(function() {
                    const $row = $(this).closest('tr');
                    return {
                        id: $(this).val(),
                        quantity: parseInt($row.find('.quantity-input').val(), 10)
                    };
                }).get();

                $.ajax({
                    url: "/order/create",
                    type: "post",
                    dataType: "json",
                    data: { products: orderData },
                    success: function(response) {
                        if (response.state === 200) {
                            // 假设返回的 response 包含一个订单ID
                            location.href = `apply.html?orderId=${response.orderId}`;
                        } else {
                            alert("订单生成失败，请重试");
                        }
                    },
                    error: function() {
                        alert("遇到错误，请检查连接");
                    }
                });
            });

        }
    });

    // 检查用户是否登录
    function checkLogin() {
        $.ajax({
            url:"/user/get-user",
            type:"get",
            success: function(result) {
                if (result.state == 401) {
                    alert("登陆已失效，请重新登陆");
                    location.href = "login.html"; // 跳转到登录页面
                }

            },
            error: function(err) {
                if (err.status == 401) {
                    alert("当前用户未登录，你即将回到首页");
                    location.href = "home.html"; // 跳转到首页
                }
            }
        })
    }
    checkLogin(); // 执行检查用户登录状态
</script>
</body>
</html>
